/**
 * 
 */
package com.mongoproject.database;

/**
 * @author Camaria Bevavy
 *
 * this class contains methods that read and print 
 * the content of an xml view 
 */
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import com.google.common.*;

public class XmlReader {
	String result="";
	public XmlReader(){
		
	}
	/**
	 * parse an xml file
	 * @param viewName: name of the view and name of the xml file
	 */
	
	/**
	 * read and parse an xml document
	 * @param viewFilename: name of the file
	 * @param viewName: name of the view
	 * @return string result
	 */
	public String readXMLFile(String viewFilename, String viewName){
		DocumentBuilder docbuilder = null;
		Document view = null;
		String path = viewFilename ;
		
		File xmlfile = new File(path);
		
		try {
			DocumentBuilderFactory docfactory = DocumentBuilderFactory.newInstance();
			docbuilder = docfactory.newDocumentBuilder();
		}
		catch(ParserConfigurationException e){
			System.out.println(e.getMessage());
		}
		
		try{
			view = docbuilder.parse(xmlfile);
		}
		catch(Exception e){
			System.out.println(e.getMessage());
		}
		
		NodeList list = view.getElementsByTagName(viewName);
		
		for(int x = 0; x < list.getLength(); x++){
			Node current = list.item(x);
			current.normalize();
			Print(current);
		}
		return result;
	}
	/**
	 * This method recursively print a node and its descendants
	 * @param current node to be printed
	 */
	public void Print(Node current){
		if(!current.hasChildNodes()){
			if(current.getNodeType() == Node.TEXT_NODE){
				String tag = current.getParentNode().getNodeName();
				String value = current.getNodeValue();
				value = value.replaceAll("[\n\t]", " ");
				value = value.trim();
				
				if(value.length() != 0){
					//System.out.println(tag + ": " + value);
					result += tag + ": " + value + "\n";
				}
			}
			else{
				//System.out.println("v2 " + current.getNodeName() + " child: " + current.getNodeValue());
				result += current.getNodeName() + ": " + current.getTextContent() + "\n";
			}
			//insert in a map each document and insert in a list
		}
		else if(current.hasChildNodes()){
			
			NodeList children = current.getChildNodes();
			for(int y = 0; y < children.getLength(); y++){
				current = children.item(y);
				Print(current);
			}
		}
		
	}
	
}

